/**
 * Layui 语言切换组件
 * 基于 xxpay I18n 库
 * 
 * @author xxpay
 * @version 1.0
 */
layui.define(['element', 'layer'], function(exports) {
    'use strict';
    
    var $ = layui.$,
        element = layui.element,
        layer = layui.layer;

    var LanguageSwitcher = {
        
        // 默认配置
        config: {
            elem: null,                    // 容器元素
            type: 'dropdown',              // 类型：dropdown(下拉), button(按钮), link(链接)
            position: 'right',             // 位置：left, right, center
            showFlag: true,                // 是否显示国旗图标
            showText: true,                // 是否显示文本
            autoReload: true,              // 切换后是否自动刷新页面
            languages: {                   // 支持的语言
                'zh_CN': {
                    name: '中文',
                    flag: '🇨🇳',
                    icon: 'layui-icon-fonts-code'
                },
                'en_US': {
                    name: 'English', 
                    flag: '🇺🇸',
                    icon: 'layui-icon-fonts-strong'
                }
            },
            callback: null                 // 切换回调函数
        },

        /**
         * 渲染语言切换器
         * @param {Object} options 配置选项
         */
        render: function(options) {
            var self = this;
            var opts = $.extend(true, {}, self.config, options);
            
            if (!opts.elem) {
                console.error('LanguageSwitcher: elem is required');
                return;
            }
            
            var $container = $(opts.elem);
            if ($container.length === 0) {
                console.error('LanguageSwitcher: container not found');
                return;
            }
            
            // 获取当前语言
            var currentLang = window.I18n ? window.I18n.getLocale() : 'zh_CN';
            var currentLangInfo = opts.languages[currentLang] || opts.languages['zh_CN'];
            
            // 根据类型渲染不同的UI
            switch (opts.type) {
                case 'dropdown':
                    self.renderDropdown($container, opts, currentLang, currentLangInfo);
                    break;
                case 'button':
                    self.renderButton($container, opts, currentLang, currentLangInfo);
                    break;
                case 'link':
                    self.renderLink($container, opts, currentLang, currentLangInfo);
                    break;
                default:
                    self.renderDropdown($container, opts, currentLang, currentLangInfo);
            }
            
            // 绑定切换事件
            self.bindEvents($container, opts);
            
            return self;
        },

        /**
         * 渲染下拉菜单样式
         */
        renderDropdown: function($container, opts, currentLang, currentLangInfo) {
            var html = '<div class="layui-nav-item language-switcher" lay-unselect>';
            
            // 当前语言显示
            html += '<a href="javascript:;" class="current-lang">';
            if (opts.showFlag) {
                html += '<span class="lang-flag">' + currentLangInfo.flag + '</span>';
            }
            if (opts.showText) {
                html += '<span class="lang-text">' + currentLangInfo.name + '</span>';
            }
            html += '<i class="layui-icon layui-icon-down layui-nav-more"></i>';
            html += '</a>';
            
            // 下拉菜单
            html += '<dl class="layui-nav-child">';
            for (var lang in opts.languages) {
                if (lang !== currentLang) {
                    var langInfo = opts.languages[lang];
                    html += '<dd>';
                    html += '<a href="javascript:;" data-lang="' + lang + '">';
                    if (opts.showFlag) {
                        html += '<span class="lang-flag">' + langInfo.flag + '</span>';
                    }
                    if (opts.showText) {
                        html += '<span class="lang-text">' + langInfo.name + '</span>';
                    }
                    html += '</a>';
                    html += '</dd>';
                }
            }
            html += '</dl>';
            html += '</div>';
            
            $container.html(html);
            
            // 重新渲染导航
            element.render('nav');
        },

        /**
         * 渲染按钮样式
         */
        renderButton: function($container, opts, currentLang, currentLangInfo) {
            var html = '<div class="language-switcher-buttons">';
            
            for (var lang in opts.languages) {
                var langInfo = opts.languages[lang];
                var isActive = lang === currentLang;
                var btnClass = 'layui-btn layui-btn-sm' + (isActive ? ' layui-btn-normal' : ' layui-btn-primary');
                
                html += '<button class="' + btnClass + '" data-lang="' + lang + '"';
                if (isActive) html += ' disabled';
                html += '>';
                
                if (opts.showFlag) {
                    html += '<span class="lang-flag">' + langInfo.flag + '</span>';
                }
                if (opts.showText) {
                    html += '<span class="lang-text">' + langInfo.name + '</span>';
                }
                html += '</button>';
            }
            
            html += '</div>';
            $container.html(html);
        },

        /**
         * 渲染链接样式
         */
        renderLink: function($container, opts, currentLang, currentLangInfo) {
            var html = '<div class="language-switcher-links">';
            
            var langArray = Object.keys(opts.languages);
            for (var i = 0; i < langArray.length; i++) {
                var lang = langArray[i];
                var langInfo = opts.languages[lang];
                var isActive = lang === currentLang;
                
                if (i > 0) html += ' | ';
                
                html += '<a href="javascript:;" class="lang-link' + (isActive ? ' active' : '') + '" data-lang="' + lang + '">';
                if (opts.showFlag) {
                    html += '<span class="lang-flag">' + langInfo.flag + '</span>';
                }
                if (opts.showText) {
                    html += '<span class="lang-text">' + langInfo.name + '</span>';
                }
                html += '</a>';
            }
            
            html += '</div>';
            $container.html(html);
        },

        /**
         * 绑定切换事件
         */
        bindEvents: function($container, opts) {
            var self = this;
            
            $container.on('click', '[data-lang]', function(e) {
                e.preventDefault();
                e.stopPropagation();
                
                var $this = $(this);
                var targetLang = $this.data('lang');
                
                if (!targetLang) return;
                
                // 显示加载提示
                var loadIndex = layer.load(2, {
                    content: window.I18n ? window.I18n.t('tip.loading') : '切换中...'
                });
                
                // 切换语言
                self.switchLanguage(targetLang, function(success) {
                    layer.close(loadIndex);
                    
                    if (success) {
                        // 成功提示
                        layer.msg(window.I18n ? window.I18n.t('lang.switch.success') : '语言切换成功', {
                            icon: 1,
                            time: 1500
                        });
                        
                        // 执行回调
                        if (typeof opts.callback === 'function') {
                            opts.callback(targetLang);
                        }
                        
                        // 自动刷新页面
                        if (opts.autoReload) {
                            setTimeout(function() {
                                location.reload();
                            }, 1000);
                        } else {
                            // 重新渲染组件
                            self.render(opts);
                        }
                    } else {
                        // 失败提示
                        layer.msg(window.I18n ? window.I18n.t('lang.switch.failed') : '语言切换失败', {
                            icon: 2,
                            time: 2000
                        });
                    }
                });
            });
        },

        /**
         * 切换语言
         * @param {String} lang 目标语言
         * @param {Function} callback 回调函数
         */
        switchLanguage: function(lang, callback) {
            // 使用I18n库切换语言
            if (window.I18n) {
                var success = window.I18n.setLocale(lang, false);
                if (callback) callback(success);
                return;
            }
            
            // 如果没有I18n库，直接发送请求到后端
            $.ajax({
                url: '/api/i18n/switch',
                type: 'POST',
                data: { lang: lang },
                success: function(res) {
                    if (res && res.code === 0) {
                        // 设置Cookie
                        document.cookie = 'xxpay_locale=' + lang + '; path=/; max-age=' + (365 * 24 * 60 * 60);
                        if (callback) callback(true);
                    } else {
                        if (callback) callback(false);
                    }
                },
                error: function() {
                    if (callback) callback(false);
                }
            });
        },

        /**
         * 获取当前语言
         */
        getCurrentLanguage: function() {
            if (window.I18n) {
                return window.I18n.getLocale();
            }
            
            // 从Cookie获取
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = cookies[i].trim();
                if (cookie.indexOf('xxpay_locale=') === 0) {
                    return cookie.substring('xxpay_locale='.length);
                }
            }
            
            return 'zh_CN';
        }
    };

    // 添加CSS样式
    var css = `
        .language-switcher .lang-flag {
            margin-right: 5px;
        }
        .language-switcher-buttons {
            display: inline-block;
        }
        .language-switcher-buttons .layui-btn {
            margin-right: 5px;
        }
        .language-switcher-links .lang-link {
            text-decoration: none;
            color: #333;
            padding: 2px 5px;
        }
        .language-switcher-links .lang-link:hover {
            color: #1E9FFF;
        }
        .language-switcher-links .lang-link.active {
            color: #1E9FFF;
            font-weight: bold;
        }
    `;
    
    // 插入样式
    if (!document.getElementById('language-switcher-style')) {
        var style = document.createElement('style');
        style.id = 'language-switcher-style';
        style.textContent = css;
        document.head.appendChild(style);
    }

    exports('languageSwitcher', LanguageSwitcher);
});
